from odoo import fields, models, api
from odoo.addons.rp_finance_management.functions.rp_finance_related_func import RpFinanceRelatedFunc
from odoo.exceptions import UserError
from odoo.addons.basic_configuration.functions.logger import log

ADDRESS_TYPE = [('residential', '个人'), ('commercial', '公司')]


class RpFinanceInvoice(models.Model):
    _name = 'rp.finance.invoice'
    _description = '发票'
    _rec_name = 'code'

    # 发票信息
    code = fields.Char(string='序列号', copy=False)
    issue_datetime = fields.Datetime(string='开票时间', default=fields.datetime.now())

    # 购买方
    purchaser_name = fields.Char(string='客户信息', help='抬头')
    customer_id = fields.Many2one(string='客户', comodel_name='rp.related.model', compute='depends_on_payment_record_ids', store=True)
    purchaser_address = fields.Char(string='地址')
    purchaser_address_type = fields.Selection(string='地址类型', selection=ADDRESS_TYPE)
    purchaser_phone_number = fields.Char(string='电话')

    # 销售方
    payer_name = fields.Char(string='名称')
    payer_address = fields.Char(string='地址')
    payer_address_type = fields.Selection(string='地址类型', selection=ADDRESS_TYPE)
    payer_phone_number = fields.Char(string='电话')
    # 关联模型
    advanced_document_ids = fields.Many2many(string='前置单据记录', comodel_name='rp.related.model', column1='rp_finance_invoice_id', column2='rp_related_model_id',
                                             relation='rp_finance_invoice_and_related_model_rel')
    payment_record_ids = fields.Many2many(string='支付单记录', comodel_name='rp.payment', column1='rp_finance_invoice_id', column2='rp_payment_id',
                                          relation='rp_finance_invoice_rp_payment_rel')
    currency_id = fields.Many2one(string='货币单位', comodel_name='res.currency', default=lambda self: self.env.company.currency_id)
    rp_finance_invoice_ids = fields.One2many(string='发票明细', comodel_name='rp.finance.invoice.line', inverse_name='rp_ship_order_invoice_id')
    service_price = fields.Float(string='总金额', compute='depends_on_invoice_line_ids', digits=(12, 3))
    tax_price = fields.Float(string='总税额', compute='depends_on_invoice_line_ids', digits=(12, 3))
    total_price = fields.Float(string='价税总计', compute='depends_on_invoice_line_ids', digits=(12, 3))

    remark = fields.Char(string='备注')

    """
    Native
    """

    @api.model_create_single
    def create(self, values):
        values['code'] = self.env['ir.sequence'].next_by_code('rp.finance.invoice') or '/'
        return super(RpFinanceInvoice, self).create(values)

    """
    Depends
    """

    @api.depends('rp_finance_invoice_ids')
    def depends_on_invoice_line_ids(self):
        service_price, tax_price, total_price = 0.0, 0.0, 0.0
        for record in self:
            for item in record.rp_finance_invoice_ids:
                service_price += item.amount_price
                tax_price += item.tax_amount
            total_price = service_price + tax_price
            record.write({'service_price': service_price, 'tax_price': tax_price, 'total_price': total_price})

    @api.depends('payment_record_ids')
    def depends_on_payment_record_ids(self):
        for record in self:
            if record.payment_record_ids:
                # rp_related_model
                customer_id = record.payment_record_ids[0].customer_id
                self.write({'customer_id': customer_id.id})
            else:
                self.write({'customer_id': False})

    def fill_customer_record(self):
        """
        填充客户记录
        """
        records = self.browse(self.env.context.get('active_ids'))
        for record in records:
            record.depends_on_payment_record_ids()

    """
    Button Function
    """

    def upstream_order_record_view(self):
        """
        获取前置单据的视图信息
        """
        log('触发了前置单据上查按钮！')
        if self.advanced_document_ids:
            result = RpFinanceRelatedFunc(self.env).forward_to_upstream_tree(self.advanced_document_ids)
            log('返回视图成功！')
            return result
        else:
            log('没有来源，无法打开视图！')
            raise UserError("没有来源，无法打开视图")


class RpShipOrderInvoice(models.Model):
    _name = 'rp.ship.order.invoice'
    _description = '保持源系统一致(重新安装系统可删除)'
    inherit = ['rp.finance.invoice']


INVOICE_LINE_TYPE = [('mail_route', '邮路'), ('fulfillment', '头尾程'), ('value_added', '增值服务')]


class RpFinanceInvoiceLine(models.Model):
    _name = 'rp.finance.invoice.line'
    _description = '发票明细'

    rp_ship_order_invoice_id = fields.Many2one(string='关联主表', comodel_name='rp.finance.invoice')
    description = fields.Char(string='描述')
    type = fields.Selection(string='类型', selection=INVOICE_LINE_TYPE)
    amount_price = fields.Float(string='金额', digits=(12, 3))
    tax_rate = fields.Float(string='税率', digits=(12, 3))
    tax_amount = fields.Float(string='税额', digits=(12, 3))
    currency_id = fields.Many2one(string='货币单位', comodel_name='res.currency', default=lambda self: self.env.company.currency_id)


class RpShipOrderInvoiceLine(models.Model):
    _name = 'rp.ship.order.invoice.line'
    _description = '保持源系统一致(重新安装系统可删除)'
    inherit = ['rp.finance.invoice.line']
